# 在 MouseClickEvent.py 文件末尾添加以下代码
import ctypes
import threading
import time

import pyperclip
from PyQt6.QtCore import QTimer, pyqtSignal, QObject
from pynput import keyboard, mouse

from service.WordTransService import query_word
from utils.TextTools import is_english_text
from widget.WordPopup import WordPopup


class HotkeyEvent(QObject):
    """处理系统级快捷键事件的类"""

    # 定义信号，用于从快捷键监听线程安全地传递信息到主线程
    show_popup_signal = pyqtSignal(int, int, dict)
    close_popup_signal = pyqtSignal()

    def __init__(self, main_window=None):
        super().__init__()
        self.main_window = main_window
        self.popup = None
        self.hotkey_listener = None
        self.hotkey_thread = None

        # 连接信号到槽函数
        self.show_popup_signal.connect(self._create_and_show_popup)
        self.close_popup_signal.connect(self.close_popup)

    def set_main_window(self, main_window):
        """设置主窗口引用"""
        self.main_window = main_window

    def start_system_hotkey_listener(self):
        """启动系统级快捷键监听器，监听 f2"""

        def on_activate():
            """当按下 f2 时的回调函数"""
            print("检测到 f2 快捷键")

            # 获取鼠标当前位置
            mouse_controller = mouse.Controller()
            x, y = mouse_controller.position

            # 处理快捷键事件
            self.on_hotkey_activated(x, y)

        # 创建快捷键监听器
        self.hotkey_listener = keyboard.GlobalHotKeys({
            '<f2>': on_activate
        })

        # 在独立线程中启动监听器
        self.hotkey_thread = threading.Thread(target=self.hotkey_listener.start)
        self.hotkey_thread.daemon = True
        self.hotkey_thread.start()

    def on_hotkey_activated(self, x, y):
        """当检测到 f2 快捷键时的回调函数"""
        print(f"快捷键事件处理: 位置({x}, {y})")

        # 获取选中的文本
        selected_text = self.get_selected_text()
        selected_text = selected_text.strip()
        # 将选中的文本转换为小写
        selected_text = selected_text.lower()

        if is_english_text(selected_text):
            # 将选中的文本复制到剪贴板
            pyperclip.copy(selected_text)
            print(f"选中的文本已复制到剪贴板: {selected_text}")

            # 查询单词
            word_info = query_word(selected_text)
            if word_info:
                # 通过信号在主线程中显示弹窗
                self.show_popup_signal.emit(int(x), int(y), word_info)
        else:
            pass

    def get_selected_text(self):
        """
        获取当前选中的文本
        通过模拟 Ctrl+C 操作来获取选中文本
        """
        try:
            # 保存当前剪贴板内容
            original_clipboard = pyperclip.paste()
        except:
            original_clipboard = ""

        try:
            # 创建键盘控制器
            keyboard_controller = keyboard.Controller()

            # 模拟 Ctrl+C 快捷键
            keyboard_controller.press(keyboard.Key.ctrl)
            keyboard_controller.press('c')
            keyboard_controller.release('c')
            keyboard_controller.release(keyboard.Key.ctrl)

            # 等待剪贴板更新
            time.sleep(0.1)

            # 获取新的剪贴板内容
            new_clipboard = pyperclip.paste()

            # 如果剪贴板内容发生变化，说明有文本被复制
            if new_clipboard != original_clipboard:
                return new_clipboard
            else:
                return ""

        except Exception as e:
            print(f"获取选中文本时出错: {e}")
            return ""

    def _create_and_show_popup(self, x, y, word_info):
        """在主线程中创建并显示弹窗"""
        # 关闭已存在的弹窗
        self.close_popup()

        # 提取三个信息
        word = word_info.get("word")
        pronunciation = word_info.get("pronunciation")
        meaning = word_info.get("meaning")

        # 创建新的弹窗
        self.popup = WordPopup(
            word=word,
            pronunciation=pronunciation,
            meaning=meaning
        )

        # 获取屏幕尺寸
        screen_width = ctypes.windll.user32.GetSystemMetrics(0)
        screen_height = ctypes.windll.user32.GetSystemMetrics(1)

        # 调整弹窗大小并获取尺寸
        self.popup.adjustSize()
        popup_width = self.popup.width()
        popup_height = self.popup.height()

        # 设置弹窗位置（在鼠标右上角）
        popup_x = min(x + 10, screen_width - popup_width - 10)  # 右侧偏移10像素，避免超出屏幕
        popup_y = max(y - popup_height - 10, 10)  # 上方偏移10像素，避免超出屏幕顶部

        self.popup.move(popup_x, popup_y)
        self.popup.show()

        # 使用 QTimer.singleShot 在3秒后自动关闭弹窗
        QTimer.singleShot(3000, self.close_popup_signal.emit)

    def close_popup(self):
        """关闭弹窗"""
        if self.popup:
            try:
                self.popup.close()
            except:
                pass
            self.popup = None

    def show_selected_text_in_app(self, selected_text):
        """在主程序窗口中显示选中的文本"""
        if self.main_window:
            # 设置窗口位置为屏幕左侧居中
            self.set_window_position_left_center()
            # 激活主窗口
            self.main_window.show()
            self.main_window.raise_()
            self.main_window.activateWindow()

            # 切换到词汇标签页
            self.main_window.tab_widget.setCurrentIndex(0)  # 词汇标签页通常是第一个

            # 获取WordDefinitionTab实例并更新显示内容
            word_tab = self.main_window.tab_widget.widget(0)
            if word_tab and hasattr(word_tab, 'set_word_data'):
                # 设置临时的单词数据，实际应用中可能需要查询数据库获取完整信息
                word_tab.set_word_data(
                    word=f"选中的文本: {selected_text}",
                    pronunciation="/ˈseˈlektəd ˈtekst/",
                    meaning=f"您通过快捷键选中的文本内容: {selected_text}"
                )
            # 激活三秒之后，自动最小化窗口
            self.main_window.timer = threading.Timer(3, self.main_window.hide)

    def set_window_position_left_center(self):
        """设置窗口位置到屏幕左侧居中"""
        if self.main_window:
            # 获取屏幕尺寸
            screen_width = ctypes.windll.user32.GetSystemMetrics(0)
            screen_height = ctypes.windll.user32.GetSystemMetrics(1)

            # 获取窗口尺寸
            window_width = self.main_window.width()
            window_height = self.main_window.height()

            # 计算窗口位置 (左侧居中)
            x = 0  # 靠左
            y = (screen_height - window_height) // 2  # 垂直居中

            # 设置窗口位置
            self.main_window.move(x, y)
